// wait until Ext is ready
// preferecesPanel will throw an error if called before Ext.onReady

Ext.onReady(function() {
	// create application
	ExtBIND.App = function() {
		// private variables
		var toolbarPanel = new ToolbarPanel();
		var statusPanel = new StatusPanel();
		var tabPanel = new TabPanel();
		var zonePanel = new ZonePanel();
		var preferencesPanel = new PreferencesPanel();

		
		// handle event binding
		var bindEvents = function() {
			
			tabPanel.on('remove', function(self, component) {
				var node = zonePanel.getSelectionModel().getSelectedNode();
				if (node && (node.id == component.id)) {
					// unselect node if its tab is closed
					node.unselect();
				}
			});
			
			// zoneselect event
			zonePanel.on('zoneselect', function(attrs){
				tabPanel.addTab(attrs.zone);
			});
			
			zonePanel.on('remove', function(tree, parent, node){
				// close tab if open
				tabPanel.remove(tabPanel.getItem(node.id));
			});
			
			// sets focus to correct tab when selected node is clicked
			zonePanel.on('click', function(node, e) {
				if (node.isSelected()) {
					tabPanel.setActiveTab(tabPanel.getItem(node.id))
				}
			});
			
			/*	
			// selects the zone in zonePanel when that zone becomes the active tab
			tabs.on('tabchange', function(self, component) {
				var selected = zones.getSelectionModel().getSelectedNode();
				
				// be sure there are no selected zones
				if (!selected) {
					var node = zones.getNodeById(component.id);
					// check if zone really exists
					if (node != undefined) {
						node.select();
					}
				}
			});
			*/
		}; // end bindEvents
		
		// public space
		return {
			// public methods
			
			init: function() {
				// setup Ext
				Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
				Ext.QuickTips.init();
				
				// setup the event bindings
				bindEvents();
				
				// load zones from server
				zonePanel.load();
				
				var viewport = new Ext.Viewport({
					layout:'border',
					items:[
						toolbarPanel,
						statusPanel,
						preferencesPanel,
						zonePanel,
						tabPanel
					]
				}); // end viewport
			},
			test: function() {
				console.debug('test');
				
				
				
			},
			getPreferencesPanel: function() {
				return true;
			},getToolBar: function() {
				return toolbarPanel;
			}, 
			// returns app version, best not to call until server preferences are loaded
			getVersion: function() {
				try {
					var version = preferencesPanel.getServerData().getAt(0).data.appVersion;
				} catch (e) {
					// not loaded yet
					var version = 'unknown';
				}
				
				return version;
			}
		};
	}(); // end app
	
	// initialize application, now the fun starts
	ExtBIND.App.init.defer(100); // defer fixes FF3 bug

	
//	ExtBIND.App.getPreferencesPanel();
});